import { UserChannel, Channel } from '@/types/data'
import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { AppThunk } from '../../index'

// state变量类型
export interface HomeState {
  channels: Channel[]
  restChannels: Channel[]
  activeId: number
}
export const Home = createSlice({
  // 命名空间，在调用action的时候会默认的设置为action命令的前缀,避免冲突
  name: 'Home',
  // 1. 定义变量(状态数据)
  initialState: {
    channels: [],
    restChannels: [],
    activeId: 0,
  } as HomeState,
  // 2. 定义reducers更新变量(其中函数属性名作为action，在组件中可以dispatch触发reducer函数更新状态)
  reducers: {
    setChannel(state, action: PayloadAction<Channel[]>) {
      state.channels = action.payload
    },
    getrestChannel(state, action: PayloadAction<Channel[]>) {
      state.restChannels = action.payload
    },
    changeActiveId(state, action: PayloadAction<number>) {
      state.activeId = action.payload
    },
    delChannelList(state, action: PayloadAction<Channel>) {
      state.channels = state.channels.filter(
        (item) => item.id !== action.payload.id
      )
      state.restChannels.unshift(action.payload)
    },
    addChannelList(state, action: PayloadAction<Channel>) {
      state.restChannels = state.restChannels.filter(
        (item) => item.id !== action.payload.id
      )
      state.channels.push(action.payload)
    },
  },
})

// 导出action函数(组件中可以dispatch(action函数)触发reducer更新状态)
export const {
  setChannel,
  getrestChannel,
  changeActiveId,
  delChannelList,
  addChannelList,
} = Home.actions

// 导出reducer(创建store使用)
export default Home.reducer
